$(function () {

    // 只初始化基础表单功能
    initBasicForm();
    // 添加表单提交功能
    initFormSubmit();
    initBasicList();
});

// 基础表单功能
function initBasicForm() {
    const $form = $('.invoice-form');
    const $radioButtons = $('input[name="invoice-type"]');

    function updateDisplay() {
        const selectedValue = $('input[name="invoice-type"]:checked').val();
        if (selectedValue === '公司') {
            $('.company-notice').show();
            $('.taxpayer-id').show();
        } else {
            $('.company-notice').hide();
            $('.taxpayer-id').hide();
        }
    }

    updateDisplay();
    $radioButtons.change(updateDisplay);
}

// 表单提交功能
function initFormSubmit() {
    $('.invoice-form').on('submit', function (e) {
        e.preventDefault();

        const formData = {
            'invoice-type': $('input[name="invoice-type"]:checked').val(),
            'in_header': $('input[name="in_header"]').val().trim(),
            'tin': $('input[name="tin"]').val().trim()
        };


        // 表单验证
        if (!formData.in_header) {
            alert('请填写发票抬头');
            return;
        }

        if (formData['invoice-type'] === '公司' && !formData.tin) {
            alert('请填写纳税人识别号');
            return;
        }

        // 发送请求
        $.ajax({
            url: 'addInvoice',
            type: 'POST',
            data: formData,
            dataType: 'text',
            success: function (response) {
                if (response === '添加成功') {
                    alert('保存成功');
                    $('.invoice-form')[0].reset();
                    loadInvoiceList();
                } else {
                    alert('保存失败：' + response);
                }
            }
        });
    });
}

// 新添加的列表功能
function initBasicList() {
    loadInvoiceList();
}

function loadInvoiceList(pageNo = 1, pageSize = 5) {
    $.ajax({
        url: 'getInvoice',
        type: 'POST',
        dataType: 'json',
        data: {
            pageNo: pageNo,
            pageSize: pageSize
        },
        success: function (response) {
            renderInvoiceList(response);
        }
    });
}

function renderInvoiceList(response) {
    const $container = $('#invoice-list .content-card');
    $container.empty();

    if (response && response.list && response.list.length > 0) {
        const $table = $('<table class="invoice-table"></table>');

        // 添加表头
        $table.append(
            '<thead>' +
            '<tr>' +
            '<th>序号</th>' +
            '<th>抬头类型</th>' +
            '<th>发票抬头</th>' +
            '<th>纳税人识别号</th>' +
            '<th>操作</th>' +
            '</tr>' +
            '</thead>'
        );

        // 添加数据行
        const $tbody = $('<tbody></tbody>');
        response.list.forEach((invoice, index) => {
            const rowNum = (response.currPageNo - 1) * response.pageSize + index + 1;
            const tin = invoice.tin || '-';
            $tbody.append(
                '<tr>' +
                '<td>' + rowNum + '</td>' +
                '<td>' + invoice.type + '</td>' +
                '<td>' + invoice.invoice_Header + '</td>' +
                '<td>' + tin + '</td>' +
                '<td><button class="delete-btn" data-id="' + invoice.id + '">删除</button></td>' +
                '</tr>'
            );
        });

        $table.append($tbody);
        $container.append($table);

        // 如果有多页，添加分页
        if (response.totalPages > 1) {
            addPagination(response);
        }
    } else {
        showEmptyState('暂无发票记录');
    }
}

function showEmptyState(message) {
    const $container = $('#invoice-list .content-card');
    $container.html('<div class="empty-state"><p>' + message + '</p></div>');
}

// 修改后的分页功能
function addPagination(pageInfo) {
    const $pagination = $('<div class="pagination"></div>');

    // 上一页
    if (pageInfo.currPageNo > 1) {
        $pagination.append('<button class="page-btn prev">上一页</button>');
    }

    // 页码
    for (let i = 1; i <= pageInfo.totalPages; i++) {
        const isActive = i === pageInfo.currPageNo ? ' active' : '';
        $pagination.append(
            '<button class="page-btn' + isActive + '" data-page="' + i + '">' + i + '</button>'
        );
    }

    // 下一页
    if (pageInfo.currPageNo < pageInfo.totalPages) {
        $pagination.append('<button class="page-btn next">下一页</button>');
    }

    $('#invoice-list .content-card').append($pagination);

    // 绑定分页事件
    $('.page-btn').click(function () {
        const $btn = $(this);
        let targetPage;

        if ($btn.hasClass('prev')) {
            targetPage = pageInfo.currPageNo - 1;
        } else if ($btn.hasClass('next')) {
            targetPage = pageInfo.currPageNo + 1;
        } else {
            targetPage = parseInt($btn.data('page'));
        }

        loadInvoiceList(targetPage);
    });
}